package com.sptpc.learnspring.service.impl;

import com.sptpc.learnspring.controller.request.NewOrderRequest;
import com.sptpc.learnspring.controller.request.OrderItem;
import com.sptpc.learnspring.mapper.DrinkMapper;
import com.sptpc.learnspring.mapper.OrderDrinkMapper;
import com.sptpc.learnspring.mapper.OrderMapper;
import com.sptpc.learnspring.model.Drink;
import com.sptpc.learnspring.model.Order;
import com.sptpc.learnspring.model.OrderDrink;
import com.sptpc.learnspring.service.IOrderService;
import com.sptpc.learnspring.vo.OrderVO;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderDrinkMapper orderDrinkMapper;
    @Autowired
    DrinkMapper drinkMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Order addNewOrder(NewOrderRequest newOrder) {
        // 1. 插入数据到t_order表，获得回填id
        Order order = new Order();
        order.setCustomer(newOrder.getCustomer());
        // 1.1 计算总价（实际生产中需要优化流程）
        // 1.1.1 取出所有饮品id
        List<Long> ids = newOrder.getItems().stream()
                .map(item -> item.getDid())
                .collect(Collectors.toList());
        // 1.1.2 通过id查询出所有drink
        List<Drink> items = drinkMapper.selectByIds(ids);
        // 1.1.3 计算总价
        BigDecimal totalPriceAmount = BigDecimal.ZERO;
        for(OrderItem item: newOrder.getItems()) {
            BigDecimal itemPriceAmount = BigDecimal.ZERO;
            for (Drink drink: items) {
                if (drink.getId()==item.getDid()) {
                    // item总价 = 单价*数量
                    itemPriceAmount = itemPriceAmount
                            .add(drink.getPrice().getAmount()
                                    .multiply(BigDecimal.valueOf(item.getQuantity())));
                    break;
                }
            }
            // order总价 = item1总价+...+item_n总价
            totalPriceAmount = totalPriceAmount.add(itemPriceAmount);
        }
        order.setPrice(Money.of(CurrencyUnit.of("CNY"), totalPriceAmount));
        order.setCreateTime(LocalDateTime.now());
        order.setState(0);
        // 插入t_order
        orderMapper.insert(order);

        // 2. 使用回填的order id和前端传入的drink id插入数据到中间表
        for(OrderItem item: newOrder.getItems()) {
            OrderDrink od = new OrderDrink();
            od.setDrinkOrderId(order.getId());
            od.setItemsId(item.getDid());
            od.setItemsQuantity(item.getQuantity());
            orderDrinkMapper.insert(od);
        }

        // 注意(x3)：这里需要事务，保证t_order和中间表的插入必须同时成功

        return order;
    }

    @Override
    public OrderVO getOrderWithDrinksById(Long id) {
        return orderMapper.selectByPrimaryKeyWithDrinks(id);
    }
}
